const fs = require('fs')

import {
	app,
	remote
} from 'electron'
const path = require('path');

export default {
	timestampToTime: function(timestamp) {
		var date = new Date(timestamp); //* 1000时间戳为10位需*1000，时间戳为13位的话不需乘1000
		var Y = date.getFullYear() + '-';
		var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
		var D = date.getDate() + ' ';
		var h = date.getHours() + ':';
		var m = date.getMinutes() + ':';
		var s = date.getSeconds();
		return Y + M + D + h + m + s;
	},
	saveImg: function(fpath, filename) {
		var readStream = fs.createReadStream(fpath);
		var exePath = path.dirname(remote.app.getPath('exe'));
		var newPath = exePath + '/upload/' + filename + '.' + this.getImgFileExt(fpath);
		var writeStream = fs.createWriteStream(newPath);
		// readStream.on('error', callback);
		// writeStream.on('error', callback);
		readStream.on('close', function() {});
		readStream.pipe(writeStream);
		return newPath;
	},
	imgToBase64: function(path) {
		var result = '';

		var data = fs.readFileSync(path);
		// , function(err, data) {
		result = data.toString('base64');
		// });
		return this.dealBase64Start(result, path);
	},
	showBase64Img: function(fpath) {
		let base64Str = this.imgToBase64(path.dirname(remote.app.getPath('exe')) + '/upload/' + fpath)
		let ext = this.getImgFileExt(fpath);
		return 'data:image/' + ext + ';base64,' + base64Str
	},
	dealBase64Start(base64Str, fpath) {
		let ext = this.getImgFileExt(fpath);
		return 'data:image/' + ext + ';base64,' + base64Str;
	},
	getImgFileExt: function(path) {
		var index = path.lastIndexOf(".") + 1;
		return path.substring(index).toLowerCase();
	},
	preViewImg: function(file) {
		var reader = new FileReader();
		reader.readAsDataURL(file);

		return new Promise(
			resolve => (reader.onloadend = () => resolve(reader.result))
		);
		/**
		 * async Photograph() {
		      // 获取用户拍照的图片名字，显示到页面上
		      this.fileName = this.$refs.photoref.files[0].name;
		      // 获取图片base64 代码，并存放到 base64ImgData 中
		      this.base64ImgData = await this.FileReader(this.$refs.photoref.files[0]);
		    },
		    FileReader(FileInfo) {
		      // FileReader 方法参考地址：https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader
		      let reader = new FileReader();
		      // readAsDataURL 方法参考地址：https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader/readAsDataURL
		      reader.readAsDataURL(FileInfo);
		      // 监听读取操作结束
		      return new Promise(
		        resolve => (reader.onloadend = () => resolve(reader.result))
		      );
		    }
		 * */
	},
	downloadImg: function(url) {
		var _self = this;
		return new Promise(function(resolve,reject){
			let image = new Image()
			image.setAttribute('crossOrigin', 'anonymous')
			image.src = url
			image.onload = () => {
				let canvas = document.createElement('canvas')
				canvas.width = image.width
				canvas.height = image.height
				let ctx = canvas.getContext('2d')
				ctx.drawImage(image, 0, 0, image.width, image.height)
				canvas.toBlob((blob) => {
					_self.blobToBase64(blob).then(function(blobRes){
						console.log('下载成功：'+blobRes)
						resolve(blobRes)
						
					})
				})
			}
			
		});
		
	},
	blobToBase64(blob) {
		return new Promise((resolve, reject) => {
			const fileReader = new FileReader();
			fileReader.onload = (e) => {
				resolve(e.target.result);
			};
			// readAsDataURL
			fileReader.readAsDataURL(blob);
			fileReader.onerror = () => {
				reject(new Error('blobToBase64 error'));
			};
		});
	}
}
